# !/user/bin/env python
# coding=utf-8

import os
import subprocess
import uuid
import urllib.request


def extract(video_path: str, tmp_dir: str):
    if video_path.startswith("http"):
        mp4_path = download_mp4(video_path, tmp_dir)
    else:
        mp4_path = video_path
    pic_path = os.path.join(tmp_dir, '{}.jpg'.format(uuid.uuid4()))
    ffmpeg_cmd = 'ffmpeg -i {} -f image2 -ss 1 -frames:v 1 {}'.format(mp4_path, pic_path)
    # print(ffmpeg_cmd)
    ffmpeg_pipe = subprocess.Popen(ffmpeg_cmd, shell=True)
    ffmpeg_pipe.wait()
    return {'pic_path':pic_path, 'mp4_path':mp4_path}


def download_mp4(video_url: str, tmp_dir: str):
    new_video_path = os.path.join(tmp_dir, '{}.mp4'.format(video_url.split('/')[-1].split('.')[0]))
    urllib.request.urlretrieve(video_url, new_video_path)
    return new_video_path

if __name__ == '__main__':
    print(extract('https://assets.mixkit.co/videos/preview/mixkit-rain-in-the-wild-2717-small.mp4','E:/python/mixkitweb/mixkit_background/'))
